import mozjpegEncode, { MozJPEGModule } from '../../lib/mozjpeg/mozjpeg_enc';
import { initEmscriptenModule } from '../util';
import { default as imageDecode } from 'image-decode';
import path from 'path';

declare function consoleA(str: any);

namespace mozjpeg {


    export const mimeType = 'image/jpeg';


    export const extension = 'jpg';


    export enum MozJpegColorSpace {
        GRAYSCALE = 1,
        RGB,
        YCbCr,
    };


    export class EncodeOptions {
        quality: number = 85;
        baseline: boolean = false;
        arithmetic: boolean = false;
        progressive: boolean = true;
        optimize_coding: boolean = true;
        smoothing: number = 0;
        color_space: MozJpegColorSpace = MozJpegColorSpace.YCbCr;
        quant_table: number = 3;
        trellis_multipass: boolean = false;
        trellis_opt_zero: boolean = false;
        trellis_opt_table: boolean = false;
        trellis_loops: number = 1;
        auto_subsample: boolean = true;
        chroma_subsample: number = 2;
        separate_chroma_quality: boolean = false;
        chroma_quality: number = 75;
    };



    const wasmUrl = path.join(__dirname, "../../lib/mozjpeg/mozjpeg_enc.wasm");

    let emscriptenModule: MozJPEGModule;


    export async function encode(data: Buffer, options?: EncodeOptions): Promise<Uint8Array> {
        if (!emscriptenModule) {
            emscriptenModule = await initEmscriptenModule(mozjpegEncode, wasmUrl);
        }
        if (!options) {
            options = new EncodeOptions;
        }
        let imageData = imageDecode(data);
        let resultView = emscriptenModule.encode(imageData.data, imageData.width, imageData.height, options);
        let result = new Uint8Array(resultView);
        emscriptenModule.free_result();
        return result;
    }

}


export = mozjpeg;